﻿using Common;
using NB.MGJ.Common;
using NB.MGJ.Common.Helper;
using NB.MGJ.Model;
using NB.MGJ.Service;
using NB.MGJ.Service.Market;
using NB.MGJ.Service.Config;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.TenPayLib;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using WebAppModel;
using WxPayAPI;
using System.Threading;
using System.Data;
using NB.MGJ.Service.AntiFake;

namespace NB.MGJ.WebWap.Controllers
{
    public class TemplateController : Controller
    {
        //
        // GET: /TemplateDemo/
        MarketService _MarketService = new MarketService();
       TheWinningService _the = new TheWinningService();
      DBHService _dbhService = new DBHService();
        MarketingUserService _MarktUser = new MarketingUserService();
        public ActionResult Index()
        {
            #region  分享接口的参数   测试
            WXPortController wx = new WXPortController();
            int nonceStrLength = 16;

            string accessToken = wx.GetAccessToken("wxa852c112b062a24b", "5d9ea6a0d7ee323351d6270fbe0f832c")["access_token"].ToString();
            string jsapi_ticket = wx.GetJsapi_ticket(accessToken)["ticket"].ToString();
            string timestamp = wx.GetTimestamp();
            string nonceStr = wx.GetRnd(nonceStrLength, true, true, true, false, "");
            ViewBag.timestamp = timestamp;
            ViewBag.nonceStr = nonceStr;
            string url = Request.Url.AbsoluteUri.ToString();
            //拼接字符串
            string singnature = GetSignature(jsapi_ticket, nonceStr, timestamp, url);
            ViewBag.signature = singnature;
            WeiXinHelper.WriteLog("jsapi_ticket验证", "jsapi_ticket:" + jsapi_ticket + ",timestamp:" + timestamp
                + ",nonceStr:" + nonceStr + ",url:" + url + ",signature:" + singnature);
            ViewBag.appId = "wxa852c112b062a24b";
            #endregion
            return View();
        }

        private string GetSignature(string jsapi_ticket, string noncestr, string timestamp, string url )
        {
            var string1Builder = new StringBuilder();
            string1Builder.Append("jsapi_ticket=").Append(jsapi_ticket).Append("&")
                          .Append("noncestr=").Append(noncestr).Append("&")
                          .Append("timestamp=").Append(timestamp).Append("&")
                          .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);
           string string1 = string1Builder.ToString();
                WXPortController wx = new WXPortController();
                return wx.SHA1(string1.ToString());
        }

        private string Sha1(string orgStr, string encode = "UTF-8")
        {
            var sha1 = new SHA1Managed();
            var sha1bytes = System.Text.Encoding.GetEncoding(encode).GetBytes(orgStr);
            byte[] resultHash = sha1.ComputeHash(sha1bytes);
            string sha1String = BitConverter.ToString(resultHash).ToLower();
            sha1String = sha1String.Replace("-", "");
            return sha1String;
        }

  

        #region   视图    获取界面数据
        public ActionResult ActivityHome()
        {
            try
            {
                string code = Request["code"];
                config_WX wxConfigModel = (Session["wxConfig"] as config_WX);
                var user = OAuthApi.GetAccessToken(wxConfigModel.AppId, wxConfigModel.AppSecret, code);
                var userinfo = OAuthApi.GetUserInfo(user.access_token, user.openid);
                UserScanQRInfoModel Model = (Session["user"] as UserScanQRInfoModel);
                WeiXinHelper.WriteLog("UnionId", userinfo.unionid);
                //添加用户扫码信息
                Model.Uid = _MarktUser.isInsert(userinfo, Model.eCode);
                Model.userCode = code;
                Model.WXName = userinfo.nickname;
                Model.OpenID = userinfo.openid;
                //获取跟码关联的活动信息
                Marketing_Activity aModel = _MarketService.GetActivity_Issue(Model.Eid, Model.BatchId);
                if (aModel == null)
                {
                    //活动为开始界面
                    return View("WithoutView");
                }
                Model.Aid = aModel.Id;

                #region  分享 扫一扫接口的参数
                WXPortController wx = new WXPortController();
                int nonceStrLength = 16;
                string accessToken = wx.GetAccessToken(wxConfigModel.AppId, wxConfigModel.AppSecret)["access_token"].ToString();
                string jsapi_ticket = wx.GetJsapi_ticket(accessToken)["ticket"].ToString();
                string timestamp = wx.GetTimestamp();
                string nonceStr = wx.GetRnd(nonceStrLength, true, true, true, false, "");

                string url = Request.Url.AbsoluteUri.ToString();
                //拼接字符串
                string singnature = GetSignature(jsapi_ticket, nonceStr, timestamp, url);

                WeiXinHelper.WriteLog("jsapi_ticket验证", "jsapi_ticket:" + jsapi_ticket + ",timestamp:" + timestamp
                    + ",nonceStr:" + nonceStr + ",url:" + url + ",signature:" + singnature);

                ViewBag.appId = wxConfigModel.AppId;
                ViewBag.timestamp = timestamp;
                ViewBag.nonceStr = nonceStr;
                ViewBag.signature = singnature;
                //Marketing_ActivityInfo actInfo = _MarketService.GetActivityInfo(Model.Aid);
                //ViewBag.ShareImgUrl = actInfo.ShareImgUrl == null ? "" : actInfo.ShareImgUrl;
                //ViewBag.ShareContont = actInfo.ShareContont == null ? "" : actInfo.ShareContont;
                #endregion

                #region 添加扫码记录

                Marketing_TheWinning mt = new Marketing_TheWinning();
                mt.ActivityID = aModel.Id;
                mt.UserID = Model.Uid;
                mt.JiaMiCode = Model.Code;
                mt.Code = Model.JiemiCode;
                mt.Time = DateTime.Now;

 
                if (aModel.ActivityType==EnumManagement.GetEnumValue(ActivityTypeEnum.redData))
                    mt.Groupid =EnumManagement.GetEnumValue( EnumTheWinningGroup.activityRedData);
                else if(aModel.ActivityType == EnumManagement.GetEnumValue(ActivityTypeEnum.sudoku))
                    mt.Groupid = EnumManagement.GetEnumValue( EnumTheWinningGroup.activitySudoku);
             
                mt.BatchID = Convert.ToInt32(mt.Code.Substring(4, AppConst.SubBatchLen).ToString());
                string tableName = "Marketing_TheWinning" + Model.eCode;
                string uTableName = "Marketing.marketing_user" + Model.eCode;
                if (!_dbhService.TabExists("marketing", tableName))
                {
                    _the.CreateTheWinningTable(tableName);
                    _the.Insert(mt, tableName);
                }
                else if (_MarketService.IsTheWinningData("Marketing." + tableName, mt.Code, uTableName) == null)
                {
                    _the.Insert(mt, tableName);
                }

                #endregion

                Session["user"] = Model;

                return View(Model);
            }
            catch (Exception ex)
            {
                WeiXinHelper.WriteLog("ActivityHome错误", ex.ToString());
                return View("ErrorView");
                throw;
            }


            //config_WX wxConfigModel = new config_WX();
            //ManagerService _manager = new ManagerService();
            //ConfigManagerService _wxService = new ConfigManagerService();
            //string fwCode = Request["fwcode"];
            //string jiemiCode = MiMa.Jiemi(fwCode, AppConst.DigitCodeKey);
            //WeiXinHelper.WriteLog("ecode", jiemiCode.Substring(0, 4));
            //Organization_Enterprise eModel = _manager.GetEnterpriseModel(jiemiCode.Substring(0, 4)) as Organization_Enterprise;
            //if (eModel == null)
            //{
            //    return View("WithoutView");
            //}
            //int EID = eModel.ID;
            //UserScanQRInfoModel user = new UserScanQRInfoModel();
            //user.Code = fwCode;
            //user.JiemiCode = jiemiCode;
            //user.Eid = EID;
            //OAuthUserInfo userinfo = new OAuthUserInfo();
            //userinfo.openid = "51451245";
            //userinfo.nickname = "零";
            //userinfo.province = "上海";
            //userinfo.sex = 1;
            //userinfo.headimgurl = "https://15448716.h40.faiusr.com/2/7/ACgIABACGAAgpp_Q0QUoltP6qAIw9AM49AM.jpg";
            //userinfo.city = "闵行";
            //userinfo.country = "666";
            //int uid = _MarktUser.isInsert(userinfo, user.JiemiCode);
            //config_WX wxModel = _wxService.GetwxBindModel(EID);
            //wxModel.CredentialAddress = WxPayConfig.certPath + wxModel.CredentialAddress;
            //Session["wxConfig"] = wxModel;//微信配置信息
            //string appid = wxModel.AppId;
            //string secret = wxModel.AppSecret;
            //user.Code = fwCode;
            //user.OpenID = "ooDfVt8nX-a6utXxcBh5MhsuNibA";
            //user.Uid = uid;
            //user.WXName = "零";
            //Marketing_Activity aModel = _MarketService.GetActivity_Issue(EID, "0004");

            //if (aModel == null)
            //{
            //    return View("WithoutView");
            //    //return RedirectToRoute("Template", "WithoutView");
            //}

            //#region 添加扫码记录

            //Marketing_TheWinning mt = new Marketing_TheWinning();
            //mt.ActivityID = aModel.Id;
            //mt.UserID = uid;
            //mt.JiaMiCode = user.Code;
            //mt.Code = user.JiemiCode;
            //mt.Time = DateTime.Now;
            //mt.BatchID = Convert.ToInt32(mt.Code.Substring(4, AppConst.SubStrLen).ToString());
            //string tableName = "Marketing_TheWinning" + mt.Code.Substring(0, 4);
            //string uTableName = "marketing_user" + mt.Code.Substring(0, 4);
            //if (!_dbhService.TabExists("marketing", tableName))
            //{
            //    _the.CreateTheWinningTable(tableName);
            //    _the.Insert(mt, tableName);
            //}
            //else if (_MarketService.IsTheWinningData("Marketing." + tableName, user.JiemiCode, "Marketing." + uTableName) == null)
            //{
            //    _the.Insert(mt, tableName);
            //}
            //#endregion
            //user.Aid = Convert.ToInt32(aModel.ActivityInfoID);
            //Session["user"] = user;
            //return View();
        }

        public JsonResult GetInFormHtml(int tid) 
        {
            // id =12;
            var model = _MarketService.GetTemplateModel(tid);
            string data = model.GetInForm.Replace(" ", "+");
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetHtml(int id = 0)
        {
            // id =12;
            var model = _MarketService.GetTemplateModel(id);

            return Json(model,JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetHomeHtml(int id = 0)
        {
           // id =12;
            var model = _MarketService.GetTemplateModel(id);
            string data = model.ActivityHome.Replace(" ", "+");
            return Json(data);
        }
        public ActionResult MyPrizeRecord()
        {    
           return View();
        }


        public ActionResult Verification()
        {
            ViewBag.Aid = (Session["user"] as UserScanQRInfoModel).Aid;
            ViewBag.Tid = (Session["user"] as UserScanQRInfoModel).TId;
            return View();
        }

        public ActionResult PrizeDetailsShow()
        {
            ViewBag.Tid = (Session["user"] as UserScanQRInfoModel).TId;
            return View();
        }



        public ActionResult VerificationHtml(int aId)
        {
            var model = _MarketService.GetTemplateByAid(aId);
             string data = model.Verification.Replace(" ", "+");
             return Json(data);
        }

        public ActionResult PrizeDetailsShowHtml(int id)
        {
            var model = _MarketService.GetTemplateModel(id);
            string data = model.PrizeDetailsShow.Replace(" ", "+");
            return Json(data);
        }

        //没中奖页面
        public ActionResult GetError(int Tid)
        {
            ViewBag.Tid = Tid;
            return View();
        }
        public ActionResult GetErrorHtml(int Tid)
        {
            ViewBag.Tid = Tid;
            var model = _MarketService.GetTemplateModel(Tid);
            string data = model.GetError.Replace(" ", "+");
            return Json(data);
        }



        public ActionResult MyPrizeRecordHtml(int Tid)
        {
            ViewBag.Tid = Tid;
            var model = _MarketService.GetTemplateModel(Tid);
            string data = model.MyPrizeRecord.Replace(" ", "+");
            return Json(data);
        }
        //中奖页面
        public ActionResult GetSucceed(int Tid)
        {
            ViewBag.Tid = Tid;
            return View();
        }
        public ActionResult GetSucceedHtml(int Tid)
        {
            ViewBag.Tid = Tid;
            var model = _MarketService.GetTemplateModel(Tid);
            string data = model.GetSucceed.Replace(" ", "+");
            return Json(data);
        }
        //活动已领取页面
        public ActionResult GetRank(int Tid)
        {
            ViewBag.Tid = Tid;
            return View();
        }
        public ActionResult GetRankHtml(int Tid)
        {
            ViewBag.Tid = Tid;
            var model = _MarketService.GetTemplateModel(Tid);
            string data = model.GetRank.Replace(" ", "+");
            return Json(data);
        }

        public ActionResult GetYetHtml(int Tid)
        {
            ViewBag.Tid = Tid;
            var model = _MarketService.GetTemplateModel(Tid);
            string data = model.GetYet.Replace(" ", "+");
            return Json(data);
        }


        //活动规则
        public ActionResult ActivityPrizeState(int Tid)
        {
            ViewBag.Tid = Tid;
            return View();
        }


        public ActionResult ActivityRuleState(int Tid) 
        {
            ViewBag.Tid = Tid;
          //  var model = _MarketService.GetTemplateModel(Tid);
         //   string data = model.ActivityRuleState.Replace(" ", "+");
          //  return Json(data);
            return View();
        }
        public ActionResult GetRuleHtml(int Tid)
        {
            ViewBag.Tid = Tid;
            var model = _MarketService.GetTemplateModel(Tid);
            string data = model.ActivityRuleState.Replace(" ", "+");
            return Json(data);
        }
        //奖品领取成功
        public ActionResult GetFinished(int theId,int tid)
        {
            ViewBag.theId = theId;
            ViewBag.tid = tid;
            return View();
        }
      

        /// <summary>
        /// 错误界面
        /// </summary>
        /// <returns></returns>
        public ActionResult ErrorView() 
        {
            return View();
        }

         /// <summary>
         /// 没有活动
         /// </summary>
         /// <returns></returns>
        public ActionResult WithoutView() 
        {
            return View();
        }
        #endregion

        /// <summary>
        /// 获取奖项信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult GetAwards(int id)
        {
            return Json(_MarketService.GetAwardsModel(id), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取中奖纪录详细详细
        /// </summary>
        /// <param name="tId">中奖纪录ID</param>
        /// <returns></returns>
        public JsonResult GetTheWinning(int tId) 
        {
            var model = (Session["user"] as UserScanQRInfoModel);
            string eCode = model.eCode;
         return Json( _MarketService.GetTheWinning(tId,eCode),JsonRequestBehavior.AllowGet);
        }

       
       
    }
}